# -*- coding: utf-8 -*-
"""
Created on Fri Jun 09 11:08:21 2017

@author: u5390570
"""

import json 
import urllib.request 
import csv



orig_battles=[]

with open('Battles Data.csv', 'r') as csvfile:
    battlesreader = csv.reader(csvfile)
    for row in battlesreader:
        orig_battles.append(row)
   


battles=[b[1].replace('~','') for b in orig_battles]
battles=[b.replace('´','') for b in battles]
battles=[b.replace('(1st)','') for b in battles]
battles=[b.replace('(2nd)','') for b in battles]
battles=[b.replace('(3rd)','') for b in battles]
battles=[b.replace('(4th)','') for b in battles]
battles=[b.replace('¸','') for b in battles]
battles=[b.replace('¨','') for b in battles]
battles=[b.replace('`','') for b in battles]
battles=[b.replace('’','') for b in battles]
battles=[b.replace('^','') for b in battles]
battles=[b.replace('—','') for b in battles]
battles=[b.replace('#NAME','Name') for b in battles]
battles=[b.replace('Constantinople','Istanbul') for b in battles]
battles=[b.replace(' ','&') for b in battles]


part1="https://maps.googleapis.com/maps/api/geocode/json?address="
part3="XXXXXX"

latitude=[]
longitude=[]
matched=[]


    
    
    

for b in range(10893,len(battles)):
    search_query=part1+battles[b]+part3
    output=urllib.request.urlopen(search_query).read()
    output2=json.loads(output)
    if output2['status']=='ZERO_RESULTS':
        latitude.append('Not Found')
        longitude.append('Not Found')
        matched.append('Not Found')
        print('Not Found')
        print(b)
    else:
        lat=output2['results'][0]['geometry']['location']['lat']
        long=output2['results'][0]['geometry']['location']['lng']
        latitude.append(lat)
        longitude.append(long)
        matched.append(output2['results'][0]['address_components'])
        print(output2['results'][0]['address_components'])
        print(b)
                        
                
##Fixing the problem##

with (open("Locations.csv","w",encoding="utf-8")) as archive_file:
    wr=csv.writer(archive_file)
    wr.writerow(["Latitude","Longitude"]) 
    for row in zip(latitude,longitude):
        wr.writerow(row)
    

        
